package com.kt.thread.demo;

/**
 * Created by tangwy on 2016/1/12.
 */
public class ThreadLocalTest {
    private static ThreadLocalTest instance = null;
    private static ThreadLocal<ThreadLocalTest> threadLocal = new ThreadLocal<ThreadLocalTest>();

    private ThreadLocalTest() {
    }

    /**
     * 为每个线程都创建一个单例的ThreadLocalTest对象并存储到本地线程中
     * 创建一个单例对象，并存储到ThreadLocal，其实这里的单例要不要synchronized都一样，
     * 因为ThreadLocal存储的数据表示当前线程的数据，假如有A线程运行了getInstance，那么A线程中instance就不为Null了，
     * 当B线程来执行getInstance()时，instance = threadLocal.get();仍然为Null，因为B线程的ThreadLocal中还没有存储instance
     * @return
     */
    public /*synchronized*/ static ThreadLocalTest getInstance() {
        instance = threadLocal.get();
        if (instance == null) {
            instance = new ThreadLocalTest();
            threadLocal.set(instance);
        }
        return instance;
    }
}
